<?php
App::uses('AppModel', 'Model');
/**
 * SysSearch Model
 *
 */
class SysSearch extends AppModel {

/**
 * Use table
 *
 * @var mixed False or table name
 */
	public $useTable = 'sys_search';
	
	public function search($keyword){
		ClassRegistry::init('Sword');
		$sword = new Sword();
		$key = trim($keyword);
		$hash = md5($keyword);
		$search = $this->findByHash($hash);
		if($search && $search['SysSearch']['modified'] >= date('Y-m-d H:i:s',strtotime('-1 hour'))){
			$idArr = split(',',$search['SysSearch']['result']);
			$searchn = array(
				'SysSearch'=>array(
					'id'=>$search['SysSearch']['id'],
					'times'=>$search['SysSearch']['times']+1
				)
			);
			$this->save($searchn);
			$rsword = split(' ',$search['SysSearch']['sword']);
		}else{
		
			$kl = $sword->keywordList($key);
			$spt = '';
			$or = array();
			$rsword = array();
			foreach ($kl as $ks){
				$spt.=' '.$ks['word'];
				$or[] = array('Ticket.title like'=>'%'.$ks['word'].'%');
				$rsword[] = $ks['word'];
			}
			$or[] = array('Venue.title_cn like'=>'%'.$key.'%');
			
			ClassRegistry::init('Ticket');
			$ticket = new Ticket();
			$ticket->recursive = 1;
			$ticket->bindModel(array('belongsTo'=>array('Venue')));
			$ticket->unbindModel(array('belongsTo'=>array('ViewPhoto','ListPhoto','TicketScate','TicketCate','SysWebsite','SysSeo')));
			
			$ids = $ticket->find('list',array(
				'fields'=>array('Ticket.id','Ticket.title'),
				'recursive'=>1,
				'conditions'=>array(
					'OR'=>$or,
						
				)		
			));
			$idArr = array_keys($ids);
			if($search){
				$times = $search['SysSearch']['times']+1;
				$id = $search['SysSearch']['id'];
			}else{
				$times = 1;
				$id = '';
			}
			$searchn = array(
				'SysSearch'=>array(
					'id'=>$id,
					'key'=>$key,
					'hash'=>$hash,
					'sword'=>trim($spt),
					'result'=>join(',',$idArr),
					'result_count'=>count($idArr),
					'times'=>$times
				)	
			);
			$this->save($searchn);
		}
		return array('ids'=>$idArr,'sword'=>$rsword);
	}

}
